<template>
  <Card title="条件" :bordered="false" :head-style="headStyle">
    <template #extra>
      <Checkbox v-model:checked="state.isAutoExpand">
        <Tooltip>
          <template #title> 如勾选，则显示全部条件，如不勾选，则条件默认只显示一行 </template>
          自动展开
        </Tooltip>
      </Checkbox>
      <Checkbox class="ml-2" v-model:checked="state.isShowEmptyValMenu">
        <Tooltip>
          <template #title> 如勾选，则显示全部条件，如不勾选，则条件默认只显示一行 </template>
          显示空值选择菜单
        </Tooltip>
      </Checkbox>
      <a-button
        class="ml-2"
        type="primary"
        @click="handleCreate"
        :loading="loading"
        v-if="!state.hasCond"
      >
        添加查询
      </a-button>
      <a-button
        class="ml-2"
        type="primary"
        @click="handleEdit"
        :loading="loading"
        v-if="state.hasCond"
      >
        修改
      </a-button>
      <a-button
        class="ml-2"
        type="primary"
        @click="handleDelete"
        :loading="loading"
        v-if="state.hasCond"
      >
        删除
      </a-button>
    </template>
    <Row :gutter="[10, 10]">
      <Col
        :xs="24"
        :sm="24"
        :md="24"
        :lg="24"
        :xl="12"
        :xxl="8"
        :xxxl="6"
        v-for="(item, index) in list"
        :key="index"
      >
        <Card
          :title="item.name"
          :head-style="headStyle"
          :body-style="{ height: '360px', overflow: 'auto', paddingRight: '10px' }"
        >
          <Row :gutter="[10, 10]">
            <Col span="24" v-for="(el, eld) in item.fields" :key="eld">
              <Space align="center">
                <Checkbox v-model:checked="el.checked" />
                <Tooltip>
                  <template #title> {{ el.fieldTitle }} </template>
                  <div class="w-70px elipsis overflow-hidden space-nowared">{{
                    el.fieldTitle
                  }}</div>
                </Tooltip>
                <Input v-model:value="el[`fieldAlias`]" style="width: 70px" />

                <Select
                  :options="el.condOptions || []"
                  v-model:value="el[`fieldCond`]"
                  style="width: 85px"
                />
                <!-- <template
                  v-if="el.type == FormField.TYPE_DATE || el.type == FormField.TYPE_DATE_TIME"
                >
                  <Select
                    :options="timeOptions"
                    v-model:value="el[`${el.fieldDesc}_cond`]"
                    style="width: 85px"
                  />
                </template>
                <template v-else-if="el.type == FormField.TYPE_MACRO">
                  <template v-if="el.macroType == 'module_field_select'">
                    <Select
                      :options="realnameCondOptions"
                      v-model:value="el[`${el.fieldDesc}_cond`]"
                      style="width: 85px"
                    />
                  </template>
                  <template v-else>
                    <template
                      v-if="
                        el.fieldType == FormField.FIELD_TYPE_INT ||
                        el.fieldType == FormField.FIELD_TYPE_DOUBLE ||
                        el.fieldType == FormField.FIELD_TYPE_FLOAT ||
                        el.fieldType == FormField.FIELD_TYPE_LONG ||
                        el.fieldType == FormField.FIELD_TYPE_PRICE
                      "
                    >
                      <Select
                        :options="realnameCondOptions2"
                        v-model:value="el[`${el.fieldDesc}_cond`]"
                        style="width: 85px"
                      />
                    </template>
                    <template v-else>
                      <Select
                        :options="realnameCondOptions3"
                        v-model:value="el[`${el.fieldDesc}_cond`]"
                        style="width: 85px"
                      />
                    </template>
                  </template>
                </template>
                <template
                  v-else-if="
                    el.fieldType == FormField.FIELD_TYPE_INT ||
                    el.fieldType == FormField.FIELD_TYPE_DOUBLE ||
                    el.fieldType == FormField.FIELD_TYPE_FLOAT ||
                    el.fieldType == FormField.FIELD_TYPE_LONG ||
                    el.fieldType == FormField.FIELD_TYPE_PRICE
                  "
                >
                  <Select
                    :options="realnameCondOptions2"
                    v-model:value="el[`${el.fieldDesc}_cond`]"
                    style="width: 85px"
                  />
                </template>
                <template v-else>
                  <template
                    v-if="el.type == FormField.TYPE_TEXTFIELD || el.type == FormField.TYPE_TEXTAREA"
                  >
                    <Select
                      :options="realnameCondOptions8"
                      v-model:value="el[`${el.fieldDesc}_cond`]"
                      style="width: 85px"
                    />
                  </template>
                  <template v-if="el.type == FormField.TYPE_SELECT">
                    <Select
                      :options="realnameCondOptions9"
                      v-model:value="el[`${el.fieldDesc}_cond`]"
                      style="width: 85px"
                    />
                  </template>
                </template> -->
                <Space align="center">
                  <div class="w-30px">宽度</div>
                  <InputNumber v-model:value="el[`fieldWidth`]" style="width: 85px !important" />
                </Space>
                <Space align="center">
                  <div class="w-30px">默认</div>
                  <Input v-model:value="el[`fieldDefaultValue`]" style="width: 100px" />
                </Space>
              </Space>
            </Col>
          </Row>
        </Card>
      </Col>
    </Row>
    <div class="mt-2">
      <div> 注： </div>
      <div> 一行的总宽度为24，宽度如果为空，则默认为6，即1/4的宽度 </div>
      <div> 当条件为时间段或数值范围时，默认值无效 </div>
    </div>
  </Card>
</template>
<script lang="ts" setup>
  import { ref, onMounted, nextTick, h } from 'vue';
  import {
    Card,
    Row,
    Col,
    Checkbox,
    Tooltip,
    Space,
    Select,
    InputNumber,
    Input,
  } from 'ant-design-vue';
  import { headStyle } from '/@/views/pages/managerPage/managerPage.data';
  import {
    getVisualCondPage,
    getVisualCondCreate,
    getVisualCondUpdate,
    getVisualCondDel,
  } from '/@/api/module/module';
  import { isArray } from '/@/utils/is';
  import { FormField, SQLBuilder } from '/@/enums/flowManage';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { t } = useI18n();
  const { createConfirm, createMessage } = useMessage();
  const props = defineProps({
    formCode: {
      type: String,
      default: '',
    },
    moduleCode: {
      type: String,
      default: '',
    },
  });
  const list = ref<Recordable[]>([]);
  // const realnameCondOptions = [
  //   {
  //     value: '1',
  //     label: '等于',
  //   },
  //   {
  //     value: '0',
  //     label: '包含',
  //   },
  // ];
  // const realnameCondOptions2 = [
  //   {
  //     value: '&gt;',
  //     label: '大于',
  //   },
  //   {
  //     value: '&lt;',
  //     label: '小于',
  //   },
  //   {
  //     value: '&gt;=',
  //     label: '大于等于',
  //   },
  //   {
  //     value: '&lt;=',
  //     label: '小于等于',
  //   },
  //   {
  //     value: SQLBuilder.COND_TYPE_SCOPE,
  //     label: '数值范围',
  //   },
  // ];

  // <select name="<%=fieldDesc%>_cond">
  // 			  <option value="1">等于</option>
  // 			  <option value="0" selected="selected">包含</option>
  // 				<%
  // 					// 基础数据
  // 					if ("macro_flow_select".equals(ff.getMacroType())) {
  // 						MacroCtlService macroCtlService = SpringUtil.getBean(MacroCtlService.class);
  // 						IBasicSelectCtl basicSelectCtl = macroCtlService.getBasicSelectCtl();
  // 						SelectMgr sm = new SelectMgr();
  // 						SelectDb sd = sm.getSelect(basicSelectCtl.getCode(ff));
  // 						if (sd.getType() == SelectDb.TYPE_LIST) {
  // 					%>
  // 					<option value="<%=SQLBuilder.COND_TYPE_MULTI%>">多选</option>
  // 					<%
  // 						}
  // 					} else if ("macro_basic_tree_select_ctl".equals(ff.getMacroType())) {
  // 					%>
  // 					<option value="<%=SQLBuilder.COND_TYPE_MULTI%>">多选</option>
  // 					<%
  // 					}
  // 				%>
  // 			  </select>
  // const realnameCondOptions3 = [
  //   {
  //     value: '1',
  //     label: '等于',
  //   },
  //   {
  //     value: '0',
  //     label: '包含',
  //   },
  //   {
  //     value: 'SQLBuilder.COND_TYPE_MULTI',
  //     label: '多选',
  //   },
  // ];
  // const realnameCondOptions4 = [
  //   {
  //     value: '1',
  //     label: '等于',
  //   },
  //   {
  //     value: '0',
  //     label: '包含',
  //   },
  //   {
  //     value: 'SQLBuilder.COND_TYPE_MULTI',
  //     label: '多选',
  //   },
  // ];

  // const realnameCondOptions8 = [
  //   {
  //     value: '1',
  //     label: '等于',
  //   },
  //   {
  //     value: '0',
  //     label: '包含',
  //   },
  // ];
  // const realnameCondOptions9 = [
  //   {
  //     value: '1',
  //     label: '等于',
  //   },
  //   {
  //     value: SQLBuilder.COND_TYPE_MULTI,
  //     label: '多选',
  //   },
  // ];

  // const timeOptions = [
  //   {
  //     value: '0',
  //     label: '时间段',
  //   },
  //   {
  //     value: '1',
  //     label: '时间点',
  //   },
  // ];

  const loading = ref(false);
  const state = ref({
    isAutoExpand: false,
    isShowEmptyValMenu: false,
    hasCond: false,
    btnName: 'cwsBtnQuery',
  });
  //新增
  const handleCreate = async () => {
    let isValid = true;
    console.log('handleCreate list', list.value);
    list.value.forEach((form) => {
      form.fields.forEach((field) => {
        if (field.checked && !field.fieldCond) {
          if (field.fieldType == 7) {
            createMessage.warn(field.fieldTitle + ': 请选择时间点或时间段');
          } else {
            createMessage.warn(field.fieldTitle + ': 请选择判断符号');
          }
          isValid = false;
        }
      });
    });
    if (!isValid) {
      return;
    }
    try {
      loading.value = true;
      const params = {
        ...state.value,
        forms: list.value,
        moduleCode: props.moduleCode,
      };
      console.log('params', params);
      await getVisualCondCreate(params);
      state.value.hasCond = true;
      createMessage.success(t('common.opSuccess'));
    } catch (error) {
      console.log(error);
    } finally {
      loading.value = false;
    }
  };
  //修改
  const handleEdit = async () => {
    let isValid = true;
    list.value.forEach((form) => {
      form.fields.forEach((field) => {
        if (field.checked && !field.fieldCond) {
          createMessage.warn('请选择字段: ' + field.title + ' 的判断符号');
          isValid = false;
        }
      });
    });
    if (!isValid) {
      return;
    }
    console.log('sate', {
      state: state.value,
      list: list.value,
    });
    try {
      loading.value = true;
      const params = {
        ...state.value,
        forms: list.value,
        moduleCode: props.moduleCode,
      };
      console.log('params', params);
      await getVisualCondUpdate(params);
      createMessage.success(t('common.opSuccess'));
    } catch (error) {
      console.log(error);
    } finally {
      loading.value = false;
    }
  };

  //删除
  const handleDelete = async () => {
    try {
      loading.value = true;
      const params = { moduleCode: props.moduleCode, btnName: state.value.btnName };
      createConfirm({
        iconType: 'warning',
        title: () => h('span', '您确定要删除么'),
        onOk: async () => {
          await getVisualCondDel(params);
          list.value = [];
          createMessage.success(t('common.opSuccess'));
          await nextTick();
          await fetch();
        },
      });
    } catch (error) {
      console.log(error);
    } finally {
      loading.value = false;
    }
  };

  const fetch = async () => {
    await nextTick();
    const res = await getVisualCondPage({
      moduleCode: props.moduleCode,
    });
    state.value.isAutoExpand = res.isAutoExpand;
    state.value.isShowEmptyValMenu = res.isShowEmptyValMenu;
    state.value.hasCond = res.hasCond;
    state.value.btnName = res.btnName ? res.btnName : 'cwsBtnQuery';
    list.value = res.forms || [];
    list.value.forEach((item) => {
      if (item.fields && item.fields.length > 0) {
        item.fields.forEach((el) => {
          if (el.condOptions && el.condOptions.length) {
            el.condOptions.forEach((el) => {
              el.value = String(el.value);
            });
          }
        });
      }
    });
  };
  onMounted(fetch);
</script>
